package com.macro.mall.tiny.modules.pms.controller;

import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.util.ImageUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@Tag(name = "UploadController", description = "图片/文件上传")
@RequestMapping("/upload")
public class UploadsController {

    // 从配置文件读取上传目录，默认为项目根目录下的 uploads/images/
    @Value("${file.upload.path:uploads/images/}")
    private String UPLOAD_DIR;

    // 富文本编辑器上传目录
    @Value("${file.editor.upload.path:uploads/editor/}")
    private String EDITOR_UPLOAD_DIR;

    // 限制文件大小为5MB
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024;

    @Autowired
    private ImageUtil imageUtil;

    @Operation(summary = "上传图片")
    @PostMapping("/image")
    @ResponseBody
    public CommonResult<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return CommonResult.failed("上传文件不能为空");
        }

        // 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return CommonResult.failed("文件大小不能超过5MB");
        }

        try {
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();

            // 防止路径遍历攻击
            if (originalFilename != null && originalFilename.contains("..")) {
                return CommonResult.failed("文件名不合法");
            }

            // 验证文件类型
            if (!isImageFile(originalFilename)) {
                return CommonResult.failed("只允许上传图片/文件文件");
            }

            // 生成唯一文件名
            String fileExtension = getFileExtension(originalFilename);
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 使用绝对路径并规范化路径
            Path uploadPath = Paths.get(UPLOAD_DIR).toAbsolutePath().normalize();

            // 创建目标目录
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            file.transferTo(filePath.toFile());

            // 返回成功信息
            Map<String, Object> result = new HashMap<>();
            result.put("filename", uniqueFilename);
            result.put("originalFilename", originalFilename);
            result.put("url", "/uploads/images/" + uniqueFilename);
            result.put("full_url", imageUtil.buildImageUrl("/uploads/images/" + uniqueFilename));
            result.put("size", file.getSize());

            return CommonResult.success(result, "上传成功");

        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("上传失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("上传异常: " + e.getMessage());
        }
    }

    @Operation(summary = "富文本编辑器上传图片")
    @PostMapping("/editor")
    @ResponseBody
    public Map<String, Object> uploadEditorImage(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        
        // 检查文件是否为空
        if (file.isEmpty()) {
            response.put("errno", 1);
            response.put("message", "上传文件不能为空");
            return response;
        }

        // 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            response.put("errno", 1);
            response.put("message", "文件大小不能超过5MB");
            return response;
        }

        try {
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();

            // 防止路径遍历攻击
            if (originalFilename != null && originalFilename.contains("..")) {
                response.put("errno", 1);
                response.put("message", "文件名不合法");
                return response;
            }

            // 验证文件类型
            if (!isImageFile(originalFilename)) {
                response.put("errno", 1);
                response.put("message", "只允许上传图片文件");
                return response;
            }

            // 生成唯一文件名
            String fileExtension = getFileExtension(originalFilename);
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 使用绝对路径并规范化路径
            Path uploadPath = Paths.get(EDITOR_UPLOAD_DIR).toAbsolutePath().normalize();

            // 创建目标目录
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            file.transferTo(filePath.toFile());

            // 返回成功信息
            Map<String, Object> data = new HashMap<>();
            String imageUrl = "/uploads/editor/" + uniqueFilename;
            data.put("url", imageUtil.buildImageUrl(imageUrl));
            data.put("alt", originalFilename);
            
            response.put("errno", 0);
            response.put("data", data);
            return response;

        } catch (IOException e) {
            e.printStackTrace();
            response.put("errno", 1);
            response.put("message", "上传失败: " + e.getMessage());
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            response.put("errno", 1);
            response.put("message", "上传异常: " + e.getMessage());
            return response;
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename != null && filename.contains(".")) {
            return filename.substring(filename.lastIndexOf(".")).toLowerCase();
        }
        return "";
    }

    /**
     * 验证是否为图片文件
     */
    private boolean isImageFile(String filename) {
        if (filename == null) return false;

        String extension = getFileExtension(filename);
        return extension.equals(".jpg") || extension.equals(".jpeg") ||
                extension.equals(".png") || extension.equals(".gif") ||
                extension.equals(".bmp") || extension.equals(".webp");
    }
}